const path = require('path');
const multer  = require('multer');
const myUnit = require('../../express/bin/unit/myUnit.js');
const myMulterStorage = require('../../express/bin/unit/myMulterStorage.js');

let upload_code_control = function (app,rootDir) {
    /*
    * upload_code_control函数负责所有关于代码上传页面传递过来的数据的处理
    * */

    let baseUrl = '../code/';
    let codeUploadUrl = rootDir+'/codeUpload/:fileType/:userName/:codeName';
    app.use(codeUploadUrl,function (req,res,next) {
        let code_path = baseUrl+req.params.userName+'/'+req.params.codeName;
        let codeUpload = multer({storage: myMulterStorage.storage(code_path)});
        app.use(codeUploadUrl,codeUpload.single('code'),function (req,res,next) {
            /*
            * 检测数据库中该用户是否已经创建了该特效条目
            * 如果没有创建,则再查询用户数据,获取插入source_code所必要的数据
            * 如果创建了,就认为是用户的更新操作,直接用新上传的文件替换旧文件在数据库中的地址
            * */
            let db_name = 'source_code_db';
            let tableName = 'source_code_table';
            let columnName = '*';
            let condition = [];
            condition.push('author='+'\''+req.params.userName+'\'');
            condition.push('special_effect_name='+'\''+req.params.codeName+'\'');
            myUnit.myDB.sql.query(db_name,tableName,columnName,condition,function (err,results) {
                try{
                    if(results.length===0){
                        let condition = [];
                        condition.push('name=\''+req.params.userName+'\'');
                        myUnit.myDB.sql.query('user_db','user_table',columnName,condition,function (err,userResults) {
                            let tableName = 'source_code_table';
                            let columnName =
                                'special_effect_name,'+
                                'userId,'+
                                'author,' +
                                'htmlAddress,' +
                                'cssAddress,' +
                                'jsAddress';
                            let columnValue = [];
                            columnValue.push(req.params.codeName);
                            columnValue.push(userResults[0].id);
                            columnValue.push(req.params.userName);
                            columnValue.push(null);
                            columnValue.push(null);
                            columnValue.push(null);
                            myUnit.myDB.sql.insert(db_name,tableName,columnName,columnValue,undefined);
                            next();
                        });
                    }else{
                        next();
                    }
                }catch(err){
                    console.error('position:upload_code_control.js->'+codeUploadUrl);
                    console.error(err);
                }
            });
        });

        app.post(codeUploadUrl,codeUpload.single('code'),function (req,res,next) {
            /*
            * 负责接收html文件的函数
            * */
            try{
                let updateSql =
                    'update source_code_table ' +
                    'set '+req.params.fileType+'Address =\''
                    +myUnit.myCrypto.strEncode(path.resolve(req.file.path))+'\' '+
                    'where special_effect_name = \''+req.params.codeName+'\';';
                let conn = 'source_code_db';
                myUnit.myDB.sql.execute(conn,updateSql,function (err,results) {
                    if(err){
                        console.error(err);
                    }
                    res.send('ok');
                });
            }catch(err){
                console.error('position:->upload_code_control.js'+codeUploadUrl);
                console.error(err);
                res.status(500).send({ error: '错误!' });
            }
        });
        next();
    });


    let multipleUploadUrl = rootDir+'/multipleUpload/:userName/:codeName';
    app.use(multipleUploadUrl,function (req,res,next) {
        try{
            let code_path = baseUrl+req.params.userName+'/'+req.params.codeName;
            let multipleUpload = multer({storage: myMulterStorage.storage(code_path)});
            app.post(multipleUploadUrl,multipleUpload.any(),function (req,res,next) {
                /*
                * 接收多个上传文件
                * */
                res.send('ok');
            });
        }catch(err){
            console.error('position:upload_code_control.js->'+multipleUploadUrl);
            console.error(err);
            res.status(500).send({ error: '错误!' });
        }
        next();
    });

};


module.exports = upload_code_control;